package com.zhan.easyexcelorder.repository;

import com.zhan.easyexcelorder.model.SysUser;
import com.zhan.easyexcelorder.vo.SysUserVO;
import com.zhan.utils.Constants;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.Date;
import java.util.List;
import java.util.Set;

public interface SysUserRepository extends PagingAndSortingRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {

    @Query("from SysUser where phone=?1 and isDelete=?2")
    SysUser loginSelect(String username, Integer isDelete);

    @Modifying
    @Query("update SysUser set password=?2,passwordState=?3,updateTime=?4,updateUserId=?5 where id in ?1")
    Integer changePassword(List<Long> id, String password, Integer passwordState, Date updateTime, Long updateUserId);

    @Query("select password from SysUser where id=?1")
    String findPasswordById(Long id);

    @Query(value = "select u from SysUser u where u.username = ?1 or u.phone = ?2")
    SysUser getUser(String username, String phone);

    @Query(value = "select generalCode from SysUser where generalCode = ?1")
    String selectGeneralCode(String generalCode);

    @Query(value = "select snatchCode from SysUser where snatchCode = ?1")
    String selectSnatchCode(String snatchCode);

    @Query("select min(u) from SysUser as u join u.roles as r join r.sysMenus as m join u.department as d where u.isDelete=" + Constants.NOT_DEL_VALUE + " and m.operationCode=?1 and d.id in ?2 group by u.department order by d.id desc")
//    @Query("select u from SysUser as u join u.roles as r join r.sysMenus as m join u.department as d where u.isDelete=" + Constants.NOT_DEL_VALUE +" and m.operationCode=?1 and d.id in ?2 order by d.id desc")
    List<SysUser> findSysUserByApproval(String operationCode, List<Long> departmentId);

    @Query("select new cn.com.chinatelecom.callcenter.user.manage.vo.SysUserVO(u.id,u.username,u.phone,r.id,r.roleName) from SysUser as u join u.roles r where u.isDelete=" + Constants.NOT_DEL_VALUE + " and u.department.id in (?1)")
    List<SysUserVO> findAllByDepartment(List<Long> departmentId);

    @Query(value = "select id from SysUser where isDelete=" + Constants.NOT_DEL_VALUE)
    Set<Long> getUserIds();

    @Modifying
    @Query(value = "update SysUser set deviceToken=?1,deviceType=?2,updateTime=?3,updateUserId=?4 where id=?4")
    Integer changeDeviceToken(String deviceToken, Integer deviceType, Date now, Long userId);

}
